﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Sovigaz.DataProvider;
using Sovigaz.Models;
using Sovigaz.Permission.Repositories;
using Utilities;

namespace Sovigaz.Controllers
{
    public class AccountController : Controller
    {
        private readonly SovigazDbContext _context = new SovigazDbContext();

        public ActionResult Index()
        {
            return RedirectToAction("Login");
        }

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginViewModel login)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Sitemaps.ToList();
                    _context.RolePermissions.ToList();
                    _context.Roles.ToList();
                    _context.Users.ToList();

                    var userRepository = new UserRepository();
                    var user = userRepository.GetByUsername(login.Username);

                    if (user == null || Utility.MD5Encrypt(login.Password) != user.Password)
                        throw new Exception("Tên đăng nhập hoặc mật khẩu không đúng.");
                    if (!user.IsActived)
                        throw new Exception("Tài khoản đã bị ngưng hoạt động.");

                    var ticket = new FormsAuthenticationTicket(1, "UserAuthentication", DateTime.Now, DateTime.Now.AddHours(12), true
                        , user.UserID + ";" + user.Username + ";" + user.FullName, FormsAuthentication.FormsCookiePath);

                    string hashCookies = FormsAuthentication.Encrypt(ticket);
                    CookieHelper.SetCookieValue(FormsAuthentication.FormsCookieName, hashCookies);

                    return RedirectToAction("Index", "Home");
                }
            }
            catch (Exception e)
            {
                ModelState.AddModelError("error", e.Message);

            }

            return View("Login");
        }

        public ActionResult Logout()
        {
            Session.Clear();
            CookieHelper.ClearCookie(FormsAuthentication.FormsCookieName);
            FormsAuthentication.SignOut();

            return RedirectToAction("Login");
        }
    }
}
